package com.example.discover

import android.content.Context
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.discover.repository.BookDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class BookDatabaseFactory {

    private class DemoDatabaseCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {

        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)

            INSTANCE?.let { demoDatabase ->
                scope.launch {
//                    populateDatabase(demoDatabase.bookDao())
                }
            }
        }

        //initialize database with default data
        suspend fun populateDatabase(bookDao: BookDao) {
//            bookDao.deleteAll()
//            bookDao.insert(Book("A-2021","Android","100"), Book("B-2021","Java","199"))
        }
    }

    private class DemoQueryCallback : RoomDatabase.QueryCallback {
        override fun onQuery(sqlQuery: String, bindArgs: MutableList<Any>) {
            //println("QueryCallback: sqlQuery=${sqlQuery}")
        }
    }

    companion object {
        //Singleton prevents multiple instances of database opening at the same time.
        @Volatile
        private var INSTANCE : BookDatabase? = null

        fun createDatabase(context: Context, scope: CoroutineScope): BookDatabase {
            return INSTANCE ?: synchronized(this){
                val instance = Room.databaseBuilder(context.applicationContext, BookDatabase::class.java,"book_database.db")
                    .addCallback(DemoDatabaseCallback(scope))
                    .allowMainThreadQueries()
                    .build()

                INSTANCE = instance

                instance
            }
        }
    }
}